package com.syy.arrange.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Component
public class IProcessDataMethodImpl implements IProcessDataMethod {

    @Autowired
    SpringReflectUtils springReflectUtils;

    @Override
    public void processSerialData(String[] tag, Object[] params) {
        //需要串行准备的数据
        if (null != tag && tag.length > 0) {
            Arrays.stream(tag).forEach(s -> {
                String[] split = s.split("#");
                try {
                    Object o = springReflectUtils.invokeMethod(split[0], split[1], params);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    @Override
    public void processParallelData(String[] tag, Object[] params) {
        //需要并行准备的数据
        if (null != tag && tag.length > 0) {
            CompletableFuture[] array = new CompletableFuture[tag.length];
            for (int i = 0; i < tag.length; i++) {
                String[] split = tag[i].split("#");
                CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
                    try {
                        Object o = springReflectUtils.invokeMethod(split[0], split[1], params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return "success";
                });
                array[i] = completableFuture;
            }
            //等待所有异步任务结束
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(array);
            try {
                // 阻塞当前线程直到所有异步任务完成
                voidCompletableFuture.get();
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
